//
//  SelectLanguageController.swift
//  SCA
//
//  Created by tjun on 2025/9/6.
//

import UIKit

class SelectLanguageController: UIViewController {

    private var maskView: UIButton!
    private var contentView: UIView!
    private var titleView: UIView!
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.rowHeight = 44
        tableView.backgroundColor = UIColorMake(0x2E3036)
        tableView.contentInsetAdjustmentBehavior = .never;
        tableView.register(SelectLanguageCell.self, forCellReuseIdentifier: SelectLanguageCell.identifier)
        return tableView
    }()
    
    private let datas: [SelectLanguageModel] = [
        SelectLanguageModel(title: AppLanguage.english.description, language: .english, isSelected: LanguageManager.shared.currentLanguage == .english),
        SelectLanguageModel(title: AppLanguage.chineseSimplified.description, language: .chineseSimplified, isSelected: LanguageManager.shared.currentLanguage == .chineseSimplified),
        SelectLanguageModel(title: AppLanguage.chineseTraditional.description, language: .chineseTraditional, isSelected: LanguageManager.shared.currentLanguage == .chineseTraditional),
        SelectLanguageModel(title: AppLanguage.japanese.description, language: .japanese, isSelected: LanguageManager.shared.currentLanguage == .japanese),
        SelectLanguageModel(title: AppLanguage.korea.description, language: .korea, isSelected: LanguageManager.shared.currentLanguage == .korea),
    ]
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        modalPresentationStyle = .custom
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        view.backgroundColor = .clear
        
        maskView = UIButton(frame: view.bounds).addTo(view)
        maskView.backgroundColor = .black.withAlphaComponent(0)
        
        let contentW = view.width - 100
        
        contentView = UIView().addTo(view)
        contentView.backgroundColor = UIColorMake(0x2E3036)
        
        let titleView = UIView().addTo(contentView)
        titleView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(50)
        }
        
        let titleLabel = UILabel(text: "语言".localizedString, font: UIFontMediumMake(20), textColor: .white).addTo(titleView)
        titleLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        let closeButton = UIButton(type: .system)
        closeButton.setImage(UIImage(systemName: "xmark"), for: .normal)
        closeButton.tintColor = .white
        closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
        titleView.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.right.equalTo(-10)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(40)
        }
        
        tableView.addTo(contentView)
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(titleView.snp.bottom)
        }
        
        let totalH = min(self.datas.count, 5) * 44 + 72
        contentView.addCorner(radius: 18)
        contentView.frame = CGRectMake((view.width - contentW) * 0.5, (view.height - contentW) * 0.5 - 30, contentW, CGFloat(totalH))

    }
    
    @objc func closeButtonTapped() {
        dismiss(completion: nil)
    }
    
    func dismiss(completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: 0.25) {
            self.maskView.backgroundColor = .black.withAlphaComponent(0.5)
        } completion: { finishi in
            self.dismiss(animated: false, completion: completion)
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.contentView.layer.transform = CATransform3DMakeScale(0.7, 0.7, 0.7)
        self.contentView.alpha = 0.7
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: .curveEaseIn) {
            self.contentView.alpha = 1
            self.maskView.backgroundColor = .black.withAlphaComponent(0.5)
            self.contentView.layer.transform = CATransform3DMakeScale(1, 1, 1)
        }
    }
}


extension SelectLanguageController: UITableViewDataSource, UITableViewDelegate {
 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SelectLanguageCell.identifier, for: indexPath) as! SelectLanguageCell
        let model = datas[indexPath.row]
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        datas.forEach { $0.isSelected = false }

        let model = datas[indexPath.row]
        model.isSelected.toggle()
        tableView.reloadData()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
            self.dismiss()
            LanguageManager.shared.currentLanguage = model.language
        })
    }
    
}
